<?php
require_once '../../../config/common_config.php';
require_once PATH_ROOT.'/inc/global.php';
$db = createMysqlDbLink($mysql_config["of"]);
$realkey=trim($_GET['key']);
$author=$db->getValue("select `author` from `auth` where `source` like 'amazon' and `account` like '".$realkey."'");
$auth=json_decode($author,true);
/** 
 *  PHP Version 5
 *
 *  @category    Amazon
 *  @package     MarketplaceWebService
 *  @copyright   Copyright 2009 Amazon Technologies, Inc.
 *  @link        http://aws.amazon.com
 *  @license     http://aws.amazon.com/apache2.0  Apache License, Version 2.0
 *  @version     2009-01-01
 */
/******************************************************************************* 

 *  Marketplace Web Service PHP5 Library
 *  Generated: Thu May 07 13:07:36 PDT 2009
 * 
 */

/**
 * Get Report  Sample
 */

include_once ('.config.inc.php'); 

/************************************************************************
* Uncomment to configure the client instance. Configuration settings
* are:
*
* - MWS endpoint URL
* - Proxy host and port.
* - MaxErrorRetry.
***********************************************************************/
// IMPORTANT: Uncomment the approiate line for the country you wish to
// sell in:
// United States:
//$serviceUrl = "https://mws.amazonservices.com";
// United Kingdom
//$serviceUrl = "https://mws.amazonservices.co.uk";
// Germany
//$serviceUrl = "https://mws.amazonservices.de";
// France
//$serviceUrl = "https://mws.amazonservices.fr";
// Italy
//$serviceUrl = "https://mws.amazonservices.it";
if($auth['MARKETPLACE_ID']=='A1VC38T7YXB528')
$serviceUrl = "https://mws.amazonservices.jp";
// China
//$serviceUrl = "https://mws.amazonservices.com.cn";
// Canada
//$serviceUrl = "https://mws.amazonservices.ca";
// India
//$serviceUrl = "https://mws.amazonservices.in";

$config = array (
  'ServiceURL' => $serviceUrl,
  'ProxyHost' => null,
  'ProxyPort' => -1,
  'MaxErrorRetry' => 3,
);

/************************************************************************
 * Instantiate Implementation of MarketplaceWebService
 * 
 * AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY constants 
 * are defined in the .config.inc.php located in the same 
 * directory as this sample
 ***********************************************************************/
 $service = new MarketplaceWebService_Client(
     $auth['AWS_ACCESS_KEY_ID'], 
     $auth['AWS_SECRET_ACCESS_KEY'], 
     $config,
     APPLICATION_NAME,
     APPLICATION_VERSION);
 
/************************************************************************
 * Uncomment to try out Mock Service that simulates MarketplaceWebService
 * responses without calling MarketplaceWebService service.
 *
 * Responses are loaded from local XML files. You can tweak XML files to
 * experiment with various outputs during development
 *
 * XML files available under MarketplaceWebService/Mock tree
 *
 ***********************************************************************/
 // $service = new MarketplaceWebService_Mock();

/************************************************************************
 * Setup request parameters and uncomment invoke to try out 
 * sample for Get Report Action
 ***********************************************************************/
 // @TODO: set request. Action can be passed as MarketplaceWebService_Model_GetReportRequest
 // object or array of parameters
 $reportId = $_GET['gid'];
 
 $parameters = array (
   'Merchant' => $auth['MERCHANT_ID'],
   'Report' => @fopen('php://memory', 'rw+'),
   'ReportId' => $reportId,
//   'MWSAuthToken' => '<MWS Auth Token>', // Optional
 );
 $request = new MarketplaceWebService_Model_GetReportRequest($parameters);

//$request = new MarketplaceWebService_Model_GetReportRequest();
//$request->setMerchant(MERCHANT_ID);
//$request->setReport(@fopen('php://memory', 'rw+'));
//$request->setReportId($reportId);
//$request->setMWSAuthToken('<MWS Auth Token>'); // Optional
 
invokeGetReport($service, $request);

/**
  * Get Report Action Sample
  * The GetReport operation returns the contents of a report. Reports can potentially be
  * very large (>100MB) which is why we only return one report at a time, and in a
  * streaming fashion.
  *   
  * @param MarketplaceWebService_Interface $service instance of MarketplaceWebService_Interface
  * @param mixed $request MarketplaceWebService_Model_GetReport or array of parameters
  */
  function invokeGetReport(MarketplaceWebService_Interface $service, $request) 
  { global $db,$realkey;
  $time=strtotime(date("Y-m-d",time()));
      try {
              $response = $service->getReport($request);
              
              //  echo ("Service Response\n");
              //  echo ("=============================================================================\n");

               // echo("        GetReportResponse\n");
              /*   if ($response->isSetGetReportResult()) {
                  $getReportResult = $response->getGetReportResult(); 
                //  echo ("            GetReport");
                  
                 if ($getReportResult->isSetContentMd5()) {
                    echo ("                ContentMd5");
                    echo ("                " . $getReportResult->getContentMd5() . "\n");
                  }
                }*/
              /*  if ($response->isSetResponseMetadata()) { 
                    echo("            ResponseMetadata\n");
                    $responseMetadata = $response->getResponseMetadata();
                    if ($responseMetadata->isSetRequestId()) 
                    {
                        echo("                RequestId\n");
                        echo("                    " . $responseMetadata->getRequestId() . "\n");
                    }
                }*/
                
             //   echo ("        Report Contents\n");
                $result=stream_get_contents($request->getReport());
				$rs=preg_split("/\r\n/",$result);
?>
<SCRIPT type=text/javascript>
function sortTable(id, col, rev) {
  var tblEl = document.getElementById(id);
  if (tblEl.reverseSort == null) {
    tblEl.reverseSort = new Array();
    tblEl.lastColumn = 1;
  }
  if (tblEl.reverseSort[col] == null)
    tblEl.reverseSort[col] = rev;
  if (col == tblEl.lastColumn)
    tblEl.reverseSort[col] = !tblEl.reverseSort[col];
  tblEl.lastColumn = col;
  var oldDsply = tblEl.style.display;
  tblEl.style.display = "";
  var tmpEl;
  var i, j;
  var minVal, minIdx;
  var testVal;
  var cmp;
  for (i = 0; i < tblEl.rows.length - 1; i++) {
    minIdx = i;
    minVal = getTextValue(tblEl.rows[i].cells[col]);
    for (j = i + 1; j < tblEl.rows.length; j++) {
      testVal = getTextValue(tblEl.rows[j].cells[col]);
      cmp = compareValues(minVal, testVal);
      if (tblEl.reverseSort[col])
        cmp = -cmp;
      if (cmp == 0  &&  col != 1)
        cmp = compareValues(getTextValue(tblEl.rows[minIdx].cells[1]),
                            getTextValue(tblEl.rows[j].cells[1]));
      if (cmp > 0) {
        minIdx = j;
        minVal = testVal;
      }
    }
    if (minIdx > i) {
      tmpEl = tblEl.removeChild(tblEl.rows[minIdx]);
      tblEl.insertBefore(tmpEl, tblEl.rows[i]);
    }
  }
  makePretty(tblEl, col);
  setRanks(tblEl, col, rev);
  tblEl.style.display = oldDsply;
  return false;
}
if (document.ELEMENT_NODE == null) {
  document.ELEMENT_NODE = 1;
  document.TEXT_NODE = 3;
}
function getTextValue(el) {
  var i;
  var s;
  s = "";
  for (i = 0; i < el.childNodes.length; i++)
    if (el.childNodes[i].nodeType == document.TEXT_NODE)
      s += el.childNodes[i].nodeValue;
    else if (el.childNodes[i].nodeType == document.ELEMENT_NODE  && 
             el.childNodes[i].tagName == "BR")
      s += " ";
    else
      s += getTextValue(el.childNodes[i]);
  return normalizeString(s);
}
function compareValues(v1, v2) {
  var f1, f2;
  f1 = parseFloat(v1);
  f2 = parseFloat(v2);
  if (!isNaN(f1)  &&  !isNaN(f2)) {
    v1 = f1;
    v2 = f2;
  }
  if (v1 == v2)
    return 0;
  if (v1 > v2)
    return 1
  return -1;
}
var whtSpEnds = new RegExp("^\\s*|\\s*$", "g");
var whtSpMult = new RegExp("\\s\\s+", "g");
function normalizeString(s) {
  s = s.replace(whtSpMult, " "); 
  s = s.replace(whtSpEnds, ""); 
  return s;
}
var rowClsNm = "alternateRow";
var colClsNm = "sortedColumn";
var rowTest = new RegExp(rowClsNm, "gi");
var colTest = new RegExp(colClsNm, "gi");
function makePretty(tblEl, col) {
  var i, j;
  var rowEl, cellEl;
  for (i = 0; i < tblEl.rows.length; i++) {
   rowEl = tblEl.rows[i];
   rowEl.className = rowEl.className.replace(rowTest, "");
    if (i % 2 != 0)
      rowEl.className += " " + rowClsNm;
    rowEl.className = normalizeString(rowEl.className);
    for (j = 2; j < tblEl.rows[i].cells.length; j++) {
      cellEl = rowEl.cells[j];
      cellEl.className = cellEl.className.replace(colTest, "");
      if (j == col)
        cellEl.className += " " + colClsNm;
      cellEl.className = normalizeString(cellEl.className);
    }
  }
  var el = tblEl.parentNode.tHead;
  rowEl = el.rows[el.rows.length - 1];
  for (i = 2; i < rowEl.cells.length; i++) {
    cellEl = rowEl.cells[i];
    cellEl.className = cellEl.className.replace(colTest, "");
    if (i == col)
      cellEl.className += " " + colClsNm;
      cellEl.className = normalizeString(cellEl.className);
  }
}
function setRanks(tblEl, col, rev) {
  var i    = 0;
  var incr = 1;
  if (tblEl.reverseSort[col])
    rev = !rev;
  if (rev) {
    incr = -1;
    i = tblEl.rows.length - 1;
  }
  var count   = 1;
  var rank    = count;
  var curVal;
  var lastVal = null;
  while (col > 1  &&  i >= 0  &&  i < tblEl.rows.length) {
    curVal = getTextValue(tblEl.rows[i].cells[col]);
    if (lastVal != null  &&  compareValues(curVal, lastVal) != 0)
        rank = count;
    tblEl.rows[i].rank = rank;
    lastVal = curVal;
    count++;
    i += incr;
  }
  var rowEl, cellEl;
  var lastRank = 0;
  for (i = 0; i < tblEl.rows.length; i++) {
    rowEl = tblEl.rows[i];
    cellEl = rowEl.cells[0];
    while (cellEl.lastChild != null)
      cellEl.removeChild(cellEl.lastChild);
    if (col > 1  &&  rowEl.rank != lastRank) {
      cellEl.appendChild(document.createTextNode(rowEl.rank));
      lastRank = rowEl.rank;
    }
  }
}
</SCRIPT>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<table border="1">
<?$rls=preg_split("/\t/",$rs[0]);?>
<tr bgcolor="#efefef">
<td><div onclick="sortTable('offTblBdy',0,false)" align="center">仓库</div></td>
<td><div onclick="sortTable('offTblBdy',1,false)" align="center">Picture</div></td>
<td><div onclick="sortTable('offTblBdy',2,false)" align="center"><?=$rls[0]?></div></td>
<td><div onclick="sortTable('offTblBdy',3,false)" align="center"><?=$rls[1]?></div></td>
<td><div onclick="sortTable('offTblBdy',4,false)" align="center"><?=$rls[2]?></div></td>
<td><div onclick="sortTable('offTblBdy',5,false)" align="center"><?=$rls[3]?></div></td>
<td><div onclick="sortTable('offTblBdy',6,false)" align="center"><?=$rls[4]?></div></td>
<td><div onclick="sortTable('offTblBdy',7,false)" align="center"><?=$rls[5]?></div></td>
</tr>
<TBODY id=offTblBdy>
<?
//mysql_query("TRUNCATE TABLE  `fbakucun`");
//$db->query("delete from `fbakucun` where `updatetime`='$time'");
$count=count($rs);
for($i=1;$i<$count;$i++){
$rels=preg_split("/\t/",$rs[$i]);

$sku=$rels[0];
	//$is_record=$db->getValue("select count(*) from `fbakucun` where `seller-sku`='$sku' and `updatetime`='$time' and `Warehouse-Condition-code`='$rels[4]'");
	//if($is_record==0){
	$sqlx="insert into `fbakucun` (`stock`,`seller-sku`,`fulfillment-channel-sku`,`asin`,`condition-type`,`Warehouse-Condition-code`,`Quantity-Available`,`updatetime`)values('$realkey','$rels[0]','$rels[1]','$rels[2]','$rels[3]','$rels[4]','$rels[5]','$time')";
	//}else{
	//	$sqlx="update `fbakucun` set `Quantity-Available`='$rels[5]' where `seller-sku`='$sku' and `updatetime`='$time' and `Warehouse-Condition-code`='$rels[4]'";
	//}
	$db->query($sqlx);
	/*$ccount=$db->getValue("select count(*) from `fbakucun` where `seller-sku` like '$sku'");*/
	/*  暂时不采集图片
	if(!is_file("../../img/".get_pic($sku))){
	$getpic=new MarketplaceWebServiceOrders_amapi_apiclass;
	$getpic->downloadPicFromAsin($rels[2],$realkey,get_pic($sku));
	}
	*/

	$total+=$rels[5];
	if($rels[4]=='SELLABLE'){
		$SELLABLE+=$rels[5];
	}
	if($rels[4]=='UNSELLABLE'){
		$UNSELLABLE+=$rels[5];
	}
?>
<tr>
<td><?=$realkey?></td>
<td><?if($i==0) {echo "picture";}else{echo "<img height='100px' width='100px' src='../../img/".get_pic($rels[0])."'/>";}?></td>
<td><?=$rels[0]?></td>
<td><?=$rels[1]?></td>
<td><?=$rels[2]?></td>
<td><?=$rels[3]?></td>
<td><?=$rels[4]?></td>
<td><?=$rels[5]?></td>
</tr>
<?
}?>
</TBODY>
</table>
共计 <?=$i?> 个SKU,<?=$total?>件货,<?=$SELLABLE?>件可售,<?=$UNSELLABLE?>件不可售
<?
            //    echo("            ResponseHeaderMetadata: " . $response->getResponseHeaderMetadata() . "\n");
     } catch (MarketplaceWebService_Exception $ex) {
         echo("Caught Exception: " . $ex->getMessage() . "\n");
         echo("Response Status Code: " . $ex->getStatusCode() . "\n");
         echo("Error Code: " . $ex->getErrorCode() . "\n");
         echo("Error Type: " . $ex->getErrorType() . "\n");
         echo("Request ID: " . $ex->getRequestId() . "\n");
         echo("XML: " . $ex->getXML() . "\n");
         echo("ResponseHeaderMetadata: " . $ex->getResponseHeaderMetadata() . "\n");
     }
 }
                                                                                
